using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class playerhealth : MonoBehaviour
{
    public float health = 100;
    public float repeatDamagePeriod = 0.2f;
    public float hurtForce = 100;
    public float hurtAmount = 35;
    public AudioClip[] audioClips;

    private SpriteRenderer healthBar;
    private Vector3 healthScale;
    private playerctrl playerctrl;
    private float lastHurt=0;
    private Animator anim;

    // Start is called before the first frame update
    void Start()
    {
        playerctrl = GetComponent<playerctrl>();
        healthBar = GameObject.Find("HealthBar").GetComponent<SpriteRenderer>();
        healthScale = healthBar.transform.localScale;
    }

    void TakeDamage(Vector3 EnemyPos)
    {
        playerctrl.bejump = false;
        Vector3 hurtVector = transform.position - EnemyPos + Vector3.up * 5;
        GetComponent<Rigidbody2D>().AddForce(hurtVector * hurtForce);
        health -= hurtAmount;
        UpdateHealthBar();
    }

    public void UpdateHealthBar()
    {
        healthBar.material.color = Color.Lerp(Color.green, Color.red, 1 - health * 0.01f);
        healthBar.transform.localScale = new Vector3(health * 0.01f * healthScale.x, 1, 1);
    }

    void ManDeath()
    {
        Collider2D[] cols = GetComponents<Collider2D>();
        foreach (Collider2D col in cols)
            col.isTrigger = true;

        SpriteRenderer[] spr = GetComponentsInChildren<SpriteRenderer>();
        foreach (SpriteRenderer s in spr)
            s.sortingLayerName = "UI";

        playerctrl.enabled = false;
        GetComponentInChildren<gun>().enabled = false;
        anim.SetTrigger("Die");
    }
    private void OnCollisionEnter2D(Collision2D col)
    {
        if (col.gameObject.tag == "Enemy")
        {
            if (Time.time > lastHurt + repeatDamagePeriod)
            {
                if (health > 0)
                {
                    TakeDamage(col.transform.position);
                    lastHurt = Time.time;
                }
                else
                {
                    ManDeath();
                }
            }
        }
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}
